import React from "react";
import TabBar from "pages/components/TabBar";
import { Route, Switch, Redirect } from "react-router-dom";
import KeepAlive, { withAliveScope, AliveScope } from "react-activation";
import { TransitionGroup, CSSTransition } from "react-transition-group";
import { inject, observer } from "mobx-react";
import navigations from "../router/index";
import { LoadingComponent } from "../index";
import ErrorBoundary from "pages/components/error";
import { mapTree } from "../../utils/index";
import { ISProduct } from "src/config";
import { locationShape, historyShape } from "src/propType";
import MenuBar from "../../pages/home/detail/menuBar";
import {tablePath} from "../router/index";

function navigationsroute(store) {
    let routes = [];
    navigations.forEach(root => {
        root.children &&
            mapTree(root.children, item => {
                if (item.path && item.component) {
                    routes.push(
                        <Route
                            key={routes.length + 1}
                            path={`/${item.path}`}
                            render={props => {
                                let name = props.match.params.id
                                    ? `/${item.path.split(":")[0]}${props.match.params.id}${
                                          props.location.search
                                      }`
                                    : `${item.path}${props.location.search}`;
                                let id = props.match.params.id ? props.match.params.id : "";
                                if (item.path.indexOf("/home") < 0) {
                                    id = id + props.location.search;
                                }
                                return (
                                    <KeepAlive id={name} name={name}>
                                        <ErrorBoundary>
                                            <item.component store={store} {...props} />
                                        </ErrorBoundary>
                                    </KeepAlive>
                                );
                            }}
                            exact
                        />,
                    );
                }
            });
    });
    return routes;
}

const routerStack = (sessionStorage.getItem("ROUTER_STACK") || "").split(",").filter(Boolean); // 路由堆栈记录
const getClassName = location => {
    const index = routerStack.lastIndexOf(location.pathname); // 最后一条记录
    if (index >= 0 && routerStack.length - 1 === index) return "forward"; // 重复打开同样的路由不增加记录
    const isLastRoute = index >= 0 && index === routerStack.length - 2; // 存在且是上一页
    const className = isLastRoute ? "back" : "forward";
    if (isLastRoute) routerStack.pop();
    else routerStack.push(location.pathname);
    sessionStorage.setItem("ROUTER_STACK", routerStack.join()); // 更改后随时保存
    return className;
};


const paths = tablePath.map(table => `/${table.path}`);

export default withAliveScope(
    observer(function (props) {
        const { store, location } = props;
        const hasTabBar = !ISProduct && ["/home", "/message", "/me"].includes(location.pathname);
        // const hasMenuBar = ["/home", ...paths].includes(location.pathname);

        const classNames = getClassName(location);
        return (
            <div
                className="app-container"
                // style={{ paddingTop: hasMenuBar ? "46px": "0px" }}
            >
                <TransitionGroup
                    className={"router-wrapper"}
                    childFactory={child => React.cloneElement(child, { classNames })}
                >
                    <CSSTransition key={location.pathname} timeout={100} unmountOnExit={true}>
                        <div className="transition-container">
                            <React.Suspense fallback={<LoadingComponent />}>
                                <Switch location={location}>
                                    {navigationsroute(store)}
                                    <Route component={props => <NotFound {...props} />} />
                                </Switch>
                            </React.Suspense>
                        </div>
                    </CSSTransition>
                </TransitionGroup>
                {/* {hasMenuBar && <MenuBar store={store} {...props}/>} */}
                {/* {hasTabBar && <TabBar {...props} />} */}
            </div>
        );
    }),
);

function NotFound(props) {
    return (
        <div className="notFound">
            <div className="img"></div>
            <div
                className="link"
                onClick={() => {
                    props.history.push("/home");
                }}
            >
                去首页
            </div>
        </div>
    );
}

NotFound.propTypes = {
    history: historyShape,
};
